<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>管理页面-用户管理</title>
    <style>
        .el-header {
            background-color: rgba(63, 157, 254, 0.99);
            color: #333;
            line-height: 90px;
        }
        .el-aside {
            color: rgb(238, 241, 246)
        }
        .el-main{

        }
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
        .upload-demo .el-upload:hover {
            border-color: #409EFF;
        }
        .upload-demo .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            height: 200px !important;
            width: 200px !important;
        }
        .avatar {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            height: 200px !important;
            width: 200px !important;
        }
        .a1{
            display: flex;
            justify-content: center;!important;
            align-items: center;!important;
            margin-top: 25px;
        }
    </style>
</head>
<body>
<div id="app">
    <!--顶部信息栏-->
    <hr style="border-width: 3px;background-color: rgba(63,157,254,0.96);border-color: rgba(63,157,254,0.96);border-style: solid">
    <el-row>
        <el-col :span="6">
            <img src="../img/logo.png" height="100" width="250" style="text-align:left;margin-left: -20px">
        </el-col>
        <el-col :span="12">
            <span class="a1" style="color:#2e2e2f;font-size:40px;">淘书网后台管理</span>
        </el-col>
        <el-col :span="6">
            <el-button type="text" style="color: #666;position: absolute; bottom: 10px;right:10px;" @click="killSession">退出登录</el-button>
            <span style="color: #666;font-size:15px;float: right;margin-top:20px">管理员:{{Admin.adminName}}</span>
        </el-col>
    </el-row>
    <hr style="border-width: 3px;background-color: rgba(63,157,254,0.96);border-color: rgba(63,157,254,0.96);border-style: solid">
    <el-container style=" border: 0px solid #eee">
        <!--左侧导航栏-->
        <el-aside width="250px" style="background-color: rgb(253,253,254);">
            <el-col style="width:250px">
                <el-menu
                        default-active="2"
                        class="el-menu-vertical-demo"
                        @open="handleOpen"
                        @close="handleClose">
                    <el-menu-item index="1" @click="jumpToBookManage">
                        <i class="el-icon-reading" index="1" style="font-size:20px"></i>
                        <span slot="title"style="font-size:20px">图书管理</span>
                    </el-menu-item>
                    <el-menu-item index="2" @click="jumpToUserManage">
                        <i class="el-icon-user" style="font-size:20px"></i>
                        <span slot="title" style="font-size:20px">用户管理</span>
                    </el-menu-item>
                    <el-menu-item index="3" @click="jumpToOrdersManage">
                        <i class="el-icon-document" style="font-size:20px"></i>
                        <span slot="title" style="font-size:20px">订单管理</span>
                    </el-menu-item>
                    <el-menu-item index="4" @click="jumpToCategoryManage">
                        <i class="el-icon-menu" style="font-size:20px"></i>
                        <span slot="title" style="font-size:20px">分类管理</span>
                    </el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>
                    <el-menu-item index="4" ></el-menu-item>

                </el-menu>
            </el-col>
        </el-aside>
        <el-main>
            <!--搜索表单-->
            <el-form ref="searchForm" :inline="true" :model="searchDialog" class="demo-form-inline" >
                <el-form-item label="性别">
                    <el-select v-model="searchDialog.gender" placeholder="Gender">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                        <el-option label="未知" value=""></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户名">
                    <el-input v-model="searchDialog.username" placeholder="Username"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
                    <el-button type="success" icon="el-icon-refresh" @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
            <el-row>
                <el-button type="primary" plain  @click="addDialogVisible = true">新增</el-button>
            </el-row>
            <!--           新增对话框           -->
            <el-dialog
                    title="新增用户"
                    :visible.sync="addDialogVisible"
                    width="30%"
            >
                <el-form ref="addForm" :model="addDialog" label-width="80px" :rules="rules">
                    <el-row>
                        <el-col :span="11.5">
                            <el-form-item label="用户名:" prop="username">
                                <el-input v-model="addDialog.username"></el-input>
                            </el-form-item>
                        </el-col >
                    </el-row>
                    <el-row>
                        <el-col :span="11.5">
                            <el-form-item label="姓名:" prop="realName">
                                <el-input v-model="addDialog.realName"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="23">
                            <el-form-item label="密码:" prop="password">
                                <el-input v-model="addDialog.password"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="性别:" prop="gender">
                                <el-select v-model="addDialog.gender" >
                                    <el-option label="男" value="男"></el-option>
                                    <el-option label="女" value="女"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="23">
                            <el-form-item style="text-align: center">
                                <el-button type="primary" @click="addUser('addForm')" >确 定</el-button>
                                <el-button @click="addDialogVisible = false" >取 消</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-dialog>
            <!--          修改对话框           -->
            <el-dialog
                    title="修改用户"
                    :visible.sync="editDialogVisible"
                    width="30%"
                   >
                <el-form ref="editForm":model="editDialog" label-width="80px" :rules="rules1">
                    <el-row>
                        <el-col >
                            <el-row>
                                <el-col :span="11.5">
                                    <el-form-item label="用户名:" prop="username">
                                        <el-input v-model="editDialog.username"></el-input>
                                    </el-form-item>
                                </el-col >
                                <el-col :span="11.5">
                                    <el-form-item label="姓名:" prop="realName">
                                        <el-input v-model="editDialog.realName"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="11.5">
                                    <el-form-item label="密码:" prop="password">
                                        <el-input v-model="editDialog.password"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="8">
                                    <el-form-item label="性别:" prop="gender">
                                        <el-select v-model="editDialog.gender" >
                                            <el-option label="男" value="男"></el-option>
                                            <el-option label="女" value="女"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="23">
                            <el-form-item style="text-align: center">
                                <el-button type="primary" @click="updateUser('editForm')" >确 定</el-button>
                                <el-button @click="editDialogVisible = false" >取 消</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-dialog>
            <!--     修改头像框    -->
            <el-dialog
                    title="更换头像"
                    :visible.sync="avatarDialogVisible"
                    width="23%"
                    >
                <el-form ref="avatarForm" :model="formData" style="width: 300px">
                    <el-form-item style="height: 200px;width: 200px">
                        <div style="margin-left:26%">
                            <el-upload
                                    class="upload-demo"
                                    action="/file/upload"
                                    :on-change="onChange"
                                    :before-upload="beforeAvatarUpload"
                                    :on-success="handleAvatarSuccess"
                                    >
                                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                <i class="el-icon-plus" style="margin-top: 110px"></i>
                            </el-upload>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <div style="margin-left:25%;margin-top:50px">
                            <el-button  type="primary"  @click="updateAvatar('avatarForm')">确认</el-button>
                            <el-button   @click="avatarDialogVisible = false">取消</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <!--表格-->
            <template>
                <el-table
                        :data="tableData"
                        style="width: 100%"
                        :row-class-name="tableRowClassName"
                        @selection-change="handleSelectionChange">
                    <el-table-column
                            align="center"
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            type="index">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            label="头像(点击更换)">
                        <template slot-scope="scope">
                            <img style="width: 100px; height: 100px;cursor: pointer"
                                 :src="scope.row.userImg"
                                 @click="echoAvatar(scope.row)">
                        </template>
                    </el-table-column>
                    <el-table-column
                            align="center"
                            prop="username"
                            label="用户名">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            prop="password"
                            label="密码">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            prop="realName"
                            label="姓名">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            prop="gender"
                            label="性别">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            prop="status"
                            label="状态" >
                        <template slot-scope="scope">
                            <el-switch
                                    v-model="scope.row.status"
                                    active-color="#13ce66"
                                    @change="changeStatus(scope.row)"
                                    inactive-color="#ff4949">
                            </el-switch>
                            <br>
                            <div>
                                <span v-if="scope.row.status == 1" style="color: #5daf34">启用</span>
                                <span v-if="scope.row.status == 0" style="color: red">禁用</span>
                            </div>

                        </template>
                    </el-table-column>
                    <el-table-column
                            align="center"
                            label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" circle  @click="echo(scope.row)"></el-button><!--修改-->
                            <el-button type="danger" icon="el-icon-delete" circle @click="deleteById(scope.row)"></el-button><!--删除-->
                        </template>
                    </el-table-column>
                </el-table>
            </template>
            <!--分页工具条-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="5"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCount"
            >
            </el-pagination>
        </el-main>
    </el-container>
</div>

<script src="../js/vue.js"></script>
<script src="../element-ui/lib/index.js"></script>
<link rel="stylesheet" href="../element-ui/lib/theme-chalk/index.css">
<script src="../js/axios-0.18.0.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>

<<script>
    new Vue({
        el: '#app',
        mounted() {
            //页面加载完成后，发送异步请求，获取所有数据
            this.loading=false;
            this.selectByPageAndCondition();
            // this.getAdmin();
        },
        methods: {
            changeStatus(row){
                console.log(row)
                if (row.status==false){
                    axios({
                        method:"post",
                        url:"/user/disable?id="+row.id,
                    }).then(resp =>{
                        if (resp.data.code==1){
                            this.$message.error('已禁用')
                            this.selectByPageAndCondition();
                        }
                    })
                }else {
                    axios({
                        method:"post",
                        url:"/user/enable?id="+row.id,
                    }).then(resp =>{
                        if (resp.data.code==1){
                            this.$message.success('已启用')
                            this.selectByPageAndCondition();
                        }
                    })
                }
            },
            getAdmin(){
                axios({
                    method:"get",
                    url:"/admin",
                }).then(resp =>{
                    this.Admin = resp.data;
                    console.log(this.Admin);
                    if (this.Admin!== null && this.Admin !== ""&& this.Admin !==undefined) {

                    }else{this.Admin={adminName:null}}
                })
            },
            killSession() {//退出登录
                this.$confirm('确认退出登录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //发送ajax请求
                    axios.get("/admin/logout").then((res) => {
                    })
                    this.$message({
                        message: '退出成功',
                        type: 'success'
                    });
                    window.location.href = "/login_page/login.html"
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            handleOpen(key, keyPath) {
                console.log(key, keyPath);
            },
            handleClose(key, keyPath) {
                console.log(key, keyPath);
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // selectAll() {
            //     var _this = this;
            //     axios({
            //         method: "post",
            //         url: "/user/selectByPage?currentPage="
            //             + _this.currentPage + "&pageSize=" + _this.pageSize,
            //         data: _this.addDialog
            //     }).then(function (resp) {
            //         //设置表格数据
            //         _this.tableData = resp.data.rows;
            //         //设置表格总记录数
            //         _this.totalCount = resp.data.totalCount;
            //     })
            // },
            //查询搜索条件内容
            selectByPageAndCondition() {
                var _this = this;
                axios({
                    method: "post",
                    url: "/user/page?currentPage="
                        + _this.currentPage + "&pageSize=" + _this.pageSize,
                    data: _this.searchDialog
                }).then(function (resp) {
                    //设置表格数据
                    _this.tableData = resp.data.items;
                    _this.tableData.forEach((item)=>{
                        if (item.status==0){
                            item.status==false
                        }else {
                            item.status=true
                        }
                    })
                    //设置表格总记录数
                    _this.totalCount = resp.data.totalCount;
                })
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                console.log(file)
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //更改头像
            updateAvatar(formName){
                var _this=this;
                axios.post("/user/update/image",
                    _this.formData).then((res) => {
                    if (res.data.code ==1) {
                        //修改成功
                        // 弹出消息提示
                        setTimeout(this.$message({
                            message:"头像修改成功",
                            type: 'success'
                        }));
                        console.log(this.formData);
                        _this.selectByPageAndCondition();
                        _this.avatarDialogVisible = false;
                        this.$refs[formName].resetFields();
                    }
                })
            },
            //重置添加框
            resetAdd() {
                if (this.$refs.addForm !== undefined){
                    this.$refs.addForm.resetFields();
                };
            },
            //重置搜索框
            resetSearch() {
                this.searchDialog = {
                    username:undefined,
                    address:undefined,
                    gender:undefined,
                    tel:undefined,
                };
                // this.$refs["form"].resetFields();不知道为什么，走到这里无效
                this.selectByPageAndCondition();
            },
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
                this.formData.userImg=res.data
            },
            onChange(file, list) {
                if (list.length > 1 && file.status !== "fail") {
                    list.splice(0, 1);
                } else if (file.status === "fail") {
                    list.splice(0, 1);
                }
            },
            //复选框
            handleSelectionChange(val) {
                this.multipleSelection = val;
                console.log(this.multipleSelection)
            },
            //每页条数
            handleSizeChange(val) {
                this.pageSize = val;
                this.selectByPageAndCondition();
                // console.log(`每页 ${val} 条`);
            },
            //当前页数
            handleCurrentChange(val) {
                this.currentPage = val;
                this.selectByPageAndCondition();
                // console.log(`当前页: ${val}`);
            },
            //查询方法
            onSubmit() {
                console.log(this.searchDialog);
                this.currentPage = 1;//每次查询回到页码到第一页
                this.selectByPageAndCondition();
            },
            //新增方法
            addUser(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var _this = this;
                        //发送ajax请求，添加数据
                        axios({
                            method: "put",
                            url: "/user",
                            data: _this.addDialog
                        }).then(function (resp) {
                            if (resp.data.code == "1") {
                                _this.$message({
                                    message: '添加成功!',
                                    type: 'success'
                                });
                                //清空重置
                                _this.resetAdd();
                                //成功后，关闭窗口
                                _this.addDialogVisible = false;
                                //更新表格数据
                                _this.selectByPageAndCondition();
                            }
                        })
                    }else {
                        this.$message({
                            message: '信息填写错误!',
                            type: 'error'
                        })
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消添加!'
                    });
                })
            },
            //回显修改信息
            echo(val) {
                var _this = this;
                _this.editDialogVisible= true;
                /**
                 * 采用深拷贝，引用类型，不会改变表单原始数据
                 * @type {any}
                 */
                _this.editDialog = JSON.parse(JSON.stringify(val));
                console.log( _this.editDialog);
            },
            echoAvatar(val){
                var _this = this;
                _this.avatarDialogVisible= true;
                _this.formData = JSON.parse(JSON.stringify(val));
                this.imageUrl=val.userImg;
            },
            //修改用户
            updateUser(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$confirm('确认是否修改该用户?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            var _this = this;
                            //发送ajax请求，修改数据
                            axios({
                                method: "post",
                                url: "/user/update",
                                data: _this.editDialog
                            }).then(function (resp) {
                                if (resp.data.code == 1) {
                                    _this.selectByPageAndCondition();
                                    _this.editDialogVisible = false;
                                    _this.$message({
                                        type: 'success',
                                        message: '修改成功!'
                                    });
                                }
                            })
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消修改！'
                            });
                       })
                    }else{
                        this.$message({
                            type: 'error',
                            message: '信息填写错误！'
                        });
                    }
                })
            },
            //删除单条数据
            deleteById(row) {
                this.id = row.id
                this.$confirm('确认是否删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var _this = this;
                    axios({
                        method: "delete",
                        url: "/user" ,
                        data: [this.id]
                    }).then(function (resp) {
                        if (resp.data.code == "1") {//删除成功
                            // 重新查询数据
                            _this.selectByPageAndCondition();

                            _this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            jumpToBookManage(){
                location.href ="bookManage.html";
            },
            jumpToUserManage(){
                location.href ="userManage.html"
            },
            jumpToOrdersManage(){
                location.href ="ordersManage.html"
            },
            jumpToCategoryManage(){
                location.href = "categoryManage.html"
            },
        },
        data() {
            //自定义用户名的校验规则 添加表单验证是否存在该用户名
            var validateUsername = (rule, value, callback) => {
                console.log(value);
                //    异步搜索
                new axios({
                    method: "get",
                    url: "/user/byUsername/"+value+"/"+0,
                }).then(resp => {
                    var result = resp.data;
                    console.log(result);
                    if (value === ''||value===null) {
                        callback(new Error('用户名不能为空'));
                    } else {
                        if (result) {
                            callback(new Error('用户名已存在'));
                        }
                        callback();
                    }
                })
            }
            //修改表单验证
            var validateUsername1 = (rule, value, callback) => {
                //    异步搜索
                new axios({
                    method: "get",
                    url: "/user/byUsername/"+value+"/"+this.editDialog.id
                }).then(resp => {
                    var result = resp.data;
                    console.log(result);
                    if (value === ''||value===null) {
                        callback(new Error('用户名不能为空'));
                    } else {
                        if (result) {
                            callback(new Error('用户名已存在'));
                        }
                        callback();
                    }
                })
            }
             return {
                //标签栏显示在”左侧“
                tabPosition: 'left',
                //当前页码
                currentPage: 1,
                // 每页显示的条数
                pageSize:5,
                // 总记录数
                totalCount:100,
                //选中id
                selectId:'',
                //管理员信息
                Admin:[],
                //新增对话框数据接收
                addDialog: {
                    id:'',
                    username: '',
                    password: '',
                    realName: '',
                    gender:'',
                    address:'',
                    tel:''
                },
                //编辑对话框数据接收
                editDialog: {
                    id:'',
                    username: '',
                    password: '',
                    realName: '',
                    gender:'',
                    address:'',
                    tel:''
                },
                //搜索框数据接受
                searchDialog: {
                    username: '',
                    address:'',
                    tel:'',
                    gender:''
                },
                //新增数据对话框显示标志
                addDialogVisible: false,
                //编辑数据对话框显示标志
                editDialogVisible: false,
                //编辑头像对话框显示标志
                avatarDialogVisible:false,
                //头像显示
                imageUrl: '',
                //编辑头像表单
                formData:{
                    id:'',
                    userImg:''
                },
                //表单规则
                rules: {
                    username: [
                        {validator: validateUsername, trigger: "blur",required: true },
                    ],
                },
                 rules1: {
                     username: [
                         {validator: validateUsername1, trigger: "blur" ,required: true },
                     ],
                 },
                //表格初始化
                tableData: [{
                    username: '',
                    userImg:'',
                    password: '',
                    realName: '',
                    gender:'加载中...',
                    address:'',
                    tel:''
                }],
            }
        }
    })
</script>
</body>
</html>